package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.Condition;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.InterviewPersonnel;
import com.yh.correct.model.JudicialDeptment;
import com.yh.correct.model.Page;
import com.yh.correct.model.Personnel;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.IRuleBreakService;
import com.yh.correct.service.impl.InterviewPersonnelServiceImpl;

/**
 * 走访登记控制层
 *
 * @author swj
 */

@RestController
@RequestMapping("/interview")
public class InterviewPersonnelController {

    /**
     * 日志记录
     */
    private static Logger logger = LogManager.getLogger(InterviewPersonnelController.class);
    /**
     * 注入走访登记服务
     */
    @Autowired
    private InterviewPersonnelServiceImpl iipl;
    @Autowired
    private IRuleBreakService rbs;

    /**
     * 增加走访登记信息
     *
     * @param interviewpersonnel
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultData addMovePersonnel(InterviewPersonnel interviewpersonnel,String date1) throws Exception {
        ResultData rd = new ResultData();
        Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(date1);
        interviewpersonnel.setDate(date2);
        int i = iipl.addInterviewPersonnel(interviewpersonnel);
        if (i > 0) {
            rd.setCode(0);
            rd.setMessage("增加成功！");
        } else {
            rd.setCode(-1);
            rd.setMessage("增加失败！");
        }
        return rd;
    }

    /**
     * 根据校正人员查找工作人员
     *
     * @param pid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getWorkByCor")
    public ResultData getWorkByCor(int pid) throws Exception {
        List<Object> list = iipl.getWorkByCor(pid);
        if(pid==0){
            return null;
        }
        ResultData rd = new ResultData();
        if (null != list) {
            rd.setCode(0);
            rd.setMessage("查询成功！");
            rd.setData(list);
        }
        return rd;
    }

    /**
     * 删除走访登记信息
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/del")
    public ResultData delInterviewPersonnel(int id) throws Exception {
        logger.debug(id);
        int i = iipl.delInterviewPersonnel(id);
        ResultData rd = new ResultData();
        if (i > 0) {
            rd.setCode(0);
            rd.setMessage("修改成功！");
        } else {
            rd.setCode(-1);
            rd.setMessage("修改失败！");
        }
        return rd;
    }

    /**
     *批量删除走访信息
     * @param list
     * @return
     * @throws Exception
     */
    @RequestMapping("/deleteBatch")
    public ResultData deleteBatch(@RequestParam("ids[]") List<Integer> list) throws Exception{
        int i=iipl.deleteBatch(list);
        ResultData rd = new ResultData();
        if (i > 0) {
            rd.setCode(0);
            rd.setMessage("删除成功！");
        } else {
            rd.setCode(-1);
            rd.setMessage("删除失败！");
        }
        return rd;
    }

    /**
     * 修改走访登记信息
     *
     * @param i
     * @return
     * @throws Exception
     */
    @RequestMapping("/edit")
    public ResultData editInterviewPersonnel(InterviewPersonnel i,String date1) throws Exception {
        Date date2=new SimpleDateFormat("yyyy-MM-dd").parse(date1);
        i.setDate(date2);
        int j = iipl.editInterviewPersonnel(i);
        ResultData rd = new ResultData();
        if (j > 0) {
            rd.setCode(0);
            rd.setMessage("修改成功！");
        } else {
            rd.setCode(-1);
            rd.setMessage("修改失败！");
        }
        return rd;
    }

    /**
     * 查询走访登记信息详情
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getId", method = RequestMethod.GET)
    public ModelAndView getIdInterviewwPersonnel(int id) throws Exception {

        InterviewPersonnel i = new InterviewPersonnel();
        i.setId(id);
        Map m = iipl.getInterviewPersonnel(i);

        return new ModelAndView("supervision/list", m);

    }

    /**
     * 进入修改页面
     *
     * @throws Exception
     */
    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    public ModelAndView getById(int id) throws Exception {

        InterviewPersonnel i = new InterviewPersonnel();
        i.setId(id);
        Map m = iipl.getInterviewPersonnel(i);
        logger.debug(m);

        return new ModelAndView("supervision/edit", m);
    }


    /**
     * 模糊查询匹配信息
     */
    @RequestMapping(value = "/getlike", method = RequestMethod.GET)
    public ResultData getLikeMovePersonnel(int pageSize, int pageNum,int jid,int pid,int perid,String startdate, String enddate) throws Exception {
        Map cont = new HashMap<>();
        cont.put("jid", jid);
        cont.put("pid", pid);
        cont.put("perid", perid);
        System.out.println(perid);
        cont.put("startdate", startdate);
        cont.put("enddate", enddate);
        cont.put("pageSize", pageSize);
        cont.put("curPageNum", pageNum);
        Page page = iipl.getLikeAdminCount(cont);
        ResultData rd = new ResultData();
        if (page != null) {
            List<Object> e = new ArrayList();
            e.add(page);
            rd.setCode(0);
            rd.setMessage("查询成功！");
            rd.setData(e);
        }
        return rd;

    }

    @RequestMapping("/page")
    public ModelAndView page(String page) {

        return new ModelAndView(page);
    }

    /**
     * 获取所有矫正单位
     *
     * @throws Exception
     */
    @RequestMapping("/getAllj")
    public ModelAndView getAllj() throws Exception {
        List<JudicialDeptment> j = rbs.getAllUnit();
        List<Object> list = iipl.getAllCorr();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("corr", list);
        map.put("job", j);
        logger.debug("map");
        return new ModelAndView("supervision/interviewadd", map);
    }


    /**
     * 根据矫正单位Id查找工作人员
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getByIdP")
    public ResultData getByIdP(Integer id) throws Exception {
        logger.debug(id);
        List<Object> list = iipl.getByIdPer(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("per", list);
        logger.debug(map);
        //return new ModelAndView("supervision/interviewadd",map);
        ResultData rd = new ResultData();
        rd.setData(list);
        return rd;
    }

    /**
     * 导出Excel
     *
     * @return
     * @throws Exception
     */

    @RequestMapping("/download")
    public String download(int[] id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "走访记录excel文件";
        // 生成选择项的导出list
        List<Map<String, Object>> projects = new ArrayList<Map<String, Object>>();
        if (id != null) {
            InterviewPersonnel ip = new InterviewPersonnel();
            for (int i : id) {
                ip.setId(i);
                Map<String, Object> m = iipl.getInterviewPersonnel(ip);
                projects.add(m);
            }
        } else {
            projects = createData();
        }
        // 填充projects数据
        List<Map<String, Object>> list = createExcelRecord(projects);
        String columnNames[] = {"序号", "矫正单位", "走访人员", "矫正人员", "走访日期", "走访场所", "走访内容", "走访状态", "走访事由"};// 列名
        String keys[] = {"id", "jname", "cname", "pname", "date", "place", "content", "state", "reson"};// map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;

    }

    /**
     * 获取所有导出对象
     *
     * @return
     * @throws Exception
     */
    private List<Map<String, Object>> createData() throws Exception {
        List<Map<String, Object>> l = iipl.getAllRuleBreak();
        return l;
    }

    /**
     * 填充数据
     *
     * @return
     */
    private List<Map<String, Object>> createExcelRecord(List<Map<String, Object>> projects) {
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "sheet1");
        listmap.add(map);
        Map<String, Object> object = null;
        for (int j = 0; j < projects.size(); j++) {
            object = projects.get(j);
            Map<String, Object> mapValue = new HashMap<String, Object>();
            mapValue.put("id", object.get("id"));
            mapValue.put("jname", object.get("jname"));
            mapValue.put("cname", object.get("cname"));
            mapValue.put("pname", object.get("pname"));
            mapValue.put("date", object.get("date"));
            mapValue.put("place", object.get("place"));
            mapValue.put("content", object.get("content"));
            mapValue.put("state", object.get("state"));
            mapValue.put("reson", object.get("reson"));
            listmap.add(mapValue);
        }
        return listmap;

    }


}
